package ws

import (
	"github.com/gorilla/websocket"
	"sync"
)

type Client struct {
	UserId int
	Conn   *websocket.Conn
}

type Manager struct {
	clients map[int]*Client
	lock    sync.RWMutex
}

var WsManager = &Manager{
	clients: make(map[int]*Client),
}

func (m *Manager) AddClient(userId int, conn *websocket.Conn) {
	m.lock.Lock()
	defer m.lock.Unlock()
	m.clients[userId] = &Client{UserId: userId, Conn: conn}
}

func (m *Manager) RemoveClient(userId int) {
	m.lock.Lock()
	defer m.lock.Unlock()
	if c, ok := m.clients[userId]; ok {
		c.Conn.Close()
		delete(m.clients, userId)
	}
}

func (m *Manager) Send(userId int, msg string) {
	m.lock.RLock()
	defer m.lock.RUnlock()
	if c, ok := m.clients[userId]; ok {
		c.Conn.WriteMessage(websocket.TextMessage, []byte(msg))
	}
}
